package com.h3c.nem.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.h3c.nem.utils.CommonUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * mybatis plus自动填充
 *
 * @author z22968
 * @date 2022-06-09 10:45
 */
@Component
public class MybatisPlusConfig implements MetaObjectHandler {
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        String account = "unknown";
        if (CommonUtil.getActivUser() != null && StringUtils.hasText(CommonUtil.getActivUser().getAccount())) {
            account = CommonUtil.getActivUser().getAccount();
        }
        setFieldValByName("createdTime", new Date(), metaObject);
        setFieldValByName("createdBy", account, metaObject);
        setFieldValByName("updateTime", new Date(), metaObject);
        setFieldValByName("updateBy", account, metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String account = "unknown";
        if (CommonUtil.getActivUser() != null && StringUtils.hasText(CommonUtil.getActivUser().getAccount())) {
            account = CommonUtil.getActivUser().getAccount();
        }
        setFieldValByName("updateTime", new Date(), metaObject);
        setFieldValByName("updateBy", account, metaObject);
    }
}
